<template>
  <div class="p-2">
    <transition name="fade">
      <div v-show="showSearch" class="mb-[10px]">
        <Card :body-style="{ padding: '16px' }">
          <div style="display: flex; align-items: center; gap: 16px; flex-wrap: wrap;">
            <div style="flex: 1; display: flex; flex-wrap: wrap; gap: 12px; align-items: center;">
              <div style="display: flex; align-items: center; gap: 8px;">
                <span style="white-space: nowrap; color: rgba(0, 0, 0, 0.85); font-size: 14px;">月份:</span>
                <Select v-model:value="queryParams.month" placeholder="请选择月份" allow-clear style="width: 120px">
                  <SelectOption value="01">1月</SelectOption>
                  <SelectOption value="02">2月</SelectOption>
                  <SelectOption value="03">3月</SelectOption>
                  <SelectOption value="04">4月</SelectOption>
                  <SelectOption value="05">5月</SelectOption>
                  <SelectOption value="06">6月</SelectOption>
                  <SelectOption value="07">7月</SelectOption>
                  <SelectOption value="08">8月</SelectOption>
                  <SelectOption value="09">9月</SelectOption>
                  <SelectOption value="10">10月</SelectOption>
                  <SelectOption value="11">11月</SelectOption>
                  <SelectOption value="12">12月</SelectOption>
                </Select>
              </div>
              <div style="display: flex; align-items: center; gap: 8px;">
                <span style="white-space: nowrap; color: rgba(0, 0, 0, 0.85); font-size: 14px;">地域:</span>
                <Select 
                  v-model:value="queryParams.region" 
                  placeholder="请选择地域" 
                  allow-clear 
                  style="width: 150px"
                  :loading="regionLoading"
                >
                  <SelectOption v-for="item in regionList" :key="item" :value="item">{{ item }}</SelectOption>
                </Select>
              </div>
              <div style="display: flex; align-items: center; gap: 8px;">
                <span style="white-space: nowrap; color: rgba(0, 0, 0, 0.85); font-size: 14px;">档位:</span>
                <Select 
                  v-model:value="queryParams.grade" 
                  placeholder="请选择档位" 
                  allow-clear 
                  style="width: 150px"
                  :loading="gradeLoading"
                >
                  <SelectOption v-for="item in gradeList" :key="item" :value="item">{{ item }}</SelectOption>
                </Select>
              </div>
              <div style="display: flex; align-items: center; gap: 8px;">
                <span style="white-space: nowrap; color: rgba(0, 0, 0, 0.85); font-size: 14px;">品牌:</span>
                <Select 
                  v-model:value="queryParams.brand" 
                  placeholder="请选择品牌" 
                  allow-clear 
                  style="width: 150px"
                  :loading="brandLoading"
                >
                  <SelectOption v-for="item in brandList" :key="item" :value="item">{{ item }}</SelectOption>
                </Select>
              </div>
              <div style="display: flex; align-items: center; gap: 8px;">
                <span style="white-space: nowrap; color: rgba(0, 0, 0, 0.85); font-size: 14px;">种类:</span>
                <Select 
                  v-model:value="queryParams.category" 
                  placeholder="请选择种类" 
                  allow-clear 
                  style="width: 150px"
                  :loading="categoryLoading"
                >
                  <SelectOption v-for="item in categoryList" :key="item" :value="item">{{ item }}</SelectOption>
                </Select>
              </div>
              <div style="display: flex; align-items: center; gap: 8px;">
                <span style="white-space: nowrap; color: rgba(0, 0, 0, 0.85); font-size: 14px;">商品名称:</span>
                <Select 
                  v-model:value="queryParams.productName" 
                  placeholder="请选择商品" 
                  allow-clear 
                  show-search
                  :filter-option="false"
                  @search="handleProductSearch"
                  style="width: 200px"
                  :loading="productLoading"
                >
                  <SelectOption v-for="item in productList" :key="item" :value="item">{{ item }}</SelectOption>
                </Select>
              </div>
            </div>
            <div style="display: flex; gap: 8px; flex-shrink: 0;">
              <Button type="primary" @click="handleQuery">预测</Button>
              <Button @click="resetQuery">重置</Button>
            </div>
          </div>
        </Card>
      </div>
    </transition>

    <Card>
      <template #title>
        <Row :gutter="10" class="mb8" style="margin-bottom: 0">
          <Col :span="1.5">
            <Button type="default" @click="handleExport" v-access:code="['data:table:export']">导出</Button>
          </Col>
          <Col :span="1.5" style="margin-left: auto">
            <Button @click="showSearch = !showSearch">{{ showSearch ? '收起' : '展开' }}</Button>
          </Col>
        </Row>
      </template>

      <Table
        :loading="loading"
        :dataSource="tableList"
        :columns="columns"
        :pagination="false"
        :row-key="(_record: any, index?: number) => index ?? 0"
        :scroll="{ x: 'max-content' }"
      >
        <template #bodyCell="{ column }">
          <template v-if="column.key === 'action'">
            <Space>
              
            </Space>
          </template>
        </template>
      </Table>

      <Pagination
        v-show="total > 0"
        :total="total"
        :current="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        show-size-changer
        :show-total="(total: number) => `共 ${total} 条`"
        @change="handlePageChange"
        @showSizeChange="handlePageSizeChange"
        style="margin-top: 16px; text-align: right"
      />
    </Card>

    <!-- 添加或修改数据对话框
    <Modal
      :title="dialog.title"
      v-model:open="dialog.visible"
      width="500px"
      :confirm-loading="buttonLoading"
      @ok="submitForm"
      @cancel="cancel"
    >
      <Form ref="tableFormRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <FormItem label="编号" name="dataCode">
          <Input v-model:value="form.dataCode" placeholder="请输入编号" />
        </FormItem>
        <FormItem label="表名" name="dataTable">
          <Input v-model:value="form.dataTable" placeholder="请输入表名" />
        </FormItem>
        <FormItem label="表中文名" name="dataTableName">
          <Input v-model:value="form.dataTableName" placeholder="请输入表中文名" />
        </FormItem>
        <FormItem label="SQL语句" name="dataSql">
          <Input.TextArea v-model:value="form.dataSql" placeholder="请输入内容" :rows="4" />
        </FormItem>
        <FormItem label="规则公式" name="dataFormula">
          <Input.TextArea v-model:value="form.dataFormula" placeholder="请输入内容" :rows="4" />
        </FormItem>
        <FormItem label="备注" name="remark">
          <Input.TextArea v-model:value="form.remark" placeholder="请输入内容" :rows="4" />
        </FormItem>
      </Form>
    </Modal> -->
  </div>
</template>

<script setup name="Table" lang="ts">
import { ref, reactive, toRefs, onMounted, computed, watch } from 'vue';
import {
  Card,
  Button,
  Table,
  Pagination,
  Row,
  Col,
  Space,
  Select,
  SelectOption,
  message,
} from 'ant-design-vue';
// 图标组件 - 使用 Ant Design Vue 内置图标或移除图标
import { listTable } from '#/api/operate/monthSalesForecast/show';
import type { TableVO, TableQuery, TableForm } from '#/api/operate/monthSalesForecast/showTypes';

const tableList = ref<TableVO[]>([]);
const allDataList = ref<TableVO[]>([]); // 存储所有数据用于客户端分页
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const regionList = ref<string[]>([]);
const regionLoading = ref(false);
const gradeList = ref<string[]>([]);
const gradeLoading = ref(false);
const brandList = ref<string[]>([]);
const brandLoading = ref(false);
const categoryList = ref<string[]>([]);
const categoryLoading = ref(false);
const productList = ref<string[]>([]);
const productLoading = ref(false);

const queryFormRef = ref();

// 基础列定义
const baseColumns = [
  {
    title: '地域',
    dataIndex: 'region',
    key: 'region',
    align: 'center' as const,
  },
  {
    title: '档位',
    dataIndex: 'grade',
    key: 'grade',
    align: 'center' as const,
  },
  {
    title: '品牌',
    dataIndex: 'brand',
    key: 'brand',
    align: 'center' as const,
  },
  {
    title: '种类',
    dataIndex: 'product_type',
    key: 'product_type',
    align: 'center' as const,
  },
  {
    title: '商品编码',
    dataIndex: 'product_code',
    key: 'product_code',
    align: 'center' as const,
  },
  {
    title: '商品名称',
    dataIndex: 'product_name',
    key: 'product_name',
    align: 'center' as const,
  },
  {
    title: '订货价',
    dataIndex: 'order_price',
    key: 'order_price',
    align: 'center' as const,
  },
  {
    title: '销售价',
    dataIndex: 'retail_price',
    key: 'retail_price',
    align: 'center' as const,
  },
];

// 根据选择的月份动态生成列
const columns = computed(() => {
  const selectedMonth = queryParams.value.month || '01';
  const monthNum = selectedMonth.padStart(2, '0');
  const monthName = parseInt(selectedMonth) + '月';
  
  return [
    ...baseColumns,
    {
      title: `2022_${monthName}_销售额(元)`,
      dataIndex: `sales_amount_2022_${monthNum}`,
      key: `sales_amount_2022_${monthNum}`,
      align: 'center' as const,
    },
    {
      title: `2023_${monthName}_销售额(元)`,
      dataIndex: `sales_amount_2023_${monthNum}`,
      key: `sales_amount_2023_${monthNum}`,
      align: 'center' as const,
    },
    {
      title: `2024_${monthName}_销售额(元)`,
      dataIndex: `sales_amount_2024_${monthNum}`,
      key: `sales_amount_2024_${monthNum}`,
      align: 'center' as const,
    },
  ];
});

const initFormData: TableForm = {
  region: undefined,
  grade: undefined,
  brand: undefined,
  product_type: undefined,
  product_code: undefined,
  product_name: undefined,
  order_price: undefined,
  retail_price: undefined,
  year: undefined,
  month: undefined,
  monthly_sales_amount: undefined,
  sales_amount_2022_01: undefined,
  sales_amount_2023_01: undefined,
  sales_amount_2024_01: undefined,
  sales_amount_2022_02: undefined,
  sales_amount_2023_02: undefined,
  sales_amount_2024_02: undefined,
  sales_amount_2022_03: undefined,
  sales_amount_2023_03: undefined,
  sales_amount_2024_03: undefined,
  sales_amount_2022_04: undefined,
  sales_amount_2023_04: undefined,
  sales_amount_2024_04: undefined,
  sales_amount_2022_05: undefined,
  sales_amount_2023_05: undefined,
  sales_amount_2024_05: undefined,
  sales_amount_2022_06: undefined,
  sales_amount_2023_06: undefined,
  sales_amount_2024_06: undefined,
  sales_amount_2022_07: undefined,
  sales_amount_2023_07: undefined,
  sales_amount_2024_07: undefined,
  sales_amount_2022_08: undefined,
  sales_amount_2023_08: undefined,
  sales_amount_2024_08: undefined,
  sales_amount_2022_09: undefined,
  sales_amount_2023_09: undefined,
  sales_amount_2024_09: undefined,
  sales_amount_2022_10: undefined,
  sales_amount_2023_10: undefined,
  sales_amount_2024_10: undefined,
  sales_amount_2022_11: undefined,
  sales_amount_2023_11: undefined,
  sales_amount_2024_11: undefined,
  sales_amount_2022_12: undefined,
  sales_amount_2023_12: undefined,
  sales_amount_2024_12: undefined
};

const data = reactive<{
  form: TableForm;
  queryParams: TableQuery & { pageNum: number; pageSize: number };
  rules: Record<string, any[]>;
}>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dataCode: undefined,
    userId: undefined,
    param: {},
    year: undefined,
    month: undefined,
    region: undefined,
    grade: undefined,
    brand: undefined,
    category: undefined,
    productName: undefined
  },
  rules: {
    dataCode: [
      { required: true, message: "编号不能为空", trigger: "blur" }
    ],
    dataTable: [
      { required: true, message: "表名不能为空", trigger: "blur" }
    ],
    dataTableName: [
      { required: true, message: "表中文名不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams } = toRefs(data);

/** 更新表格显示数据(客户端分页) */
const updateTableList = () => {
  const startIndex = (queryParams.value.pageNum - 1) * queryParams.value.pageSize;
  const endIndex = startIndex + queryParams.value.pageSize;
  tableList.value = allDataList.value.slice(startIndex, endIndex);
};

/** 查询数据列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listTable(queryParams.value);
    console.log('API 返回数据:', res);
    
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      dataList = res.rows;
    } else {
      console.warn('未知的数据结构:', res);
      dataList = [];
    }
    
    // 根据条件筛选数据
    if (queryParams.value.region) {
      dataList = dataList.filter((item: any) => 
        item.region === queryParams.value.region
      );
    }
    if (queryParams.value.grade) {
      dataList = dataList.filter((item: any) => 
        item.grade === queryParams.value.grade
      );
    }
    if (queryParams.value.brand) {
      dataList = dataList.filter((item: any) => 
        item.brand === queryParams.value.brand
      );
    }
    if (queryParams.value.category) {
      dataList = dataList.filter((item: any) => 
        item.product_type === queryParams.value.category
      );
    }
    if (queryParams.value.productName) {
      dataList = dataList.filter((item: any) => 
        item.product_name === queryParams.value.productName
      );
    }
    
    // 按档位顺序排序
    const gradeOrder = ['一档', '二档', '三档', '四档', '五档', '六档', '七档', '八档', '九档', '十档'];
    dataList.sort((a: any, b: any) => {
      const gradeA = a.grade || '';
      const gradeB = b.grade || '';
      const indexA = gradeOrder.indexOf(gradeA);
      const indexB = gradeOrder.indexOf(gradeB);
      
      if (indexA !== -1 && indexB !== -1) {
        return indexA - indexB;
      }
      if (indexA !== -1) return -1;
      if (indexB !== -1) return 1;
      return gradeA.localeCompare(gradeB, 'zh-CN');
    });
    
    // 保存全量数据用于分页
    allDataList.value = dataList;
    total.value = dataList.length;
    
    // 客户端分页
    updateTableList();
    
    console.log('处理后的表格数据:', tableList.value);
    console.log('数据总数:', total.value);
  } catch (error) {
    console.error('获取数据失败:', error);
    tableList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};


/** 导出按钮操作 */
const handleExport = async () => {
  // 构建筛选条件提示
  const conditions: string[] = [];
  if (queryParams.value.region) conditions.push(`地域:${queryParams.value.region}`);
  if (queryParams.value.grade) conditions.push(`档位:${queryParams.value.grade}`);
  if (queryParams.value.brand) conditions.push(`品牌:${queryParams.value.brand}`);
  if (queryParams.value.category) conditions.push(`种类:${queryParams.value.category}`);
  if (queryParams.value.productName) conditions.push(`商品名称:${queryParams.value.productName}`);
  if (queryParams.value.month) conditions.push(`月份:${parseInt(queryParams.value.month)}月`);
  
  const conditionText = conditions.length > 0 ? `(筛选条件: ${conditions.join(', ')})` : '(全部数据)';
  const hideLoading = message.loading(`正在导出数据${conditionText}...`, 0);
  
  try {
    // 使用当前已筛选的数据
    const dataList = tableList.value;
    
    // 检查是否有数据
    if (dataList.length === 0) {
      message.warning('当前筛选条件下没有数据可导出');
      return;
    }
    
    // 获取选择的月份
    const selectedMonth = queryParams.value.month || '01';
    const monthNum = selectedMonth.padStart(2, '0');
    const monthName = parseInt(selectedMonth) + '月';
    
    // 转换为CSV格式
    const headers = [
      '地域', '档位', '品牌', '种类', '商品编码', '商品名称', '订货价', '销售价',
      `2022_${monthName}_销售额(元)`,
      `2023_${monthName}_销售额(元)`,
      `2024_${monthName}_销售额(元)`
    ];
    const csvContent = [
      headers.join(','),
      ...dataList.map((item: any) => [
        item.region || '',
        item.grade || '',
        item.brand || '',
        item.product_type || '',
        item.product_code || '',
        item.product_name || '',
        item.order_price || '',
        item.retail_price || '',
        item[`sales_amount_2022_${monthNum}`] || '',
        item[`sales_amount_2023_${monthNum}`] || '',
        item[`sales_amount_2024_${monthNum}`] || ''
      ].join(','))
    ].join('\n');
    
    // 添加BOM头以支持中文
    const BOM = '\uFEFF';
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' });
    
    // 构建文件名
    let fileName = '月度销售额';
    if (queryParams.value.month) fileName += `_${parseInt(queryParams.value.month)}月`;
    if (queryParams.value.region) fileName += `_${queryParams.value.region}`;
    if (queryParams.value.grade) fileName += `_${queryParams.value.grade}`;
    fileName += `_${new Date().getTime()}.csv`;
    
    // 创建下载链接
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', fileName);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    message.success(`导出成功! 共导出 ${dataList.length} 条数据`);
  } catch (error) {
    console.error('导出失败:', error);
    message.error('导出失败');
  } finally {
    hideLoading();
  }
};

/** 分页变化 */
const handlePageChange = (page: number) => {
  queryParams.value.pageNum = page;
  updateTableList(); // 使用客户端分页,无需重新请求
};

/** 分页大小变化 */
const handlePageSizeChange = (_current: number, size: number) => {
  queryParams.value.pageSize = size;
  queryParams.value.pageNum = 1;
  updateTableList(); // 使用客户端分页,无需重新请求
};

// 监听搜索条件变化,实现联动筛选
watch(
  () => [queryParams.value.region, queryParams.value.grade, queryParams.value.brand, queryParams.value.category],
  () => {
    getGradeList();
    getBrandList();
    getCategoryList();
  },
  { deep: true }
);

/** 获取地域列表 */
const getRegionList = async () => {
  regionLoading.value = true;
  try {
    const res = await listTable(queryParams.value);
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      dataList = res.rows;
    }
    
    if (queryParams.value.grade) {
      dataList = dataList.filter((item: any) => item.grade === queryParams.value.grade);
    }
    if (queryParams.value.brand) {
      dataList = dataList.filter((item: any) => item.brand === queryParams.value.brand);
    }
    if (queryParams.value.category) {
      dataList = dataList.filter((item: any) => item.product_type === queryParams.value.category);
    }
    
    const regions = new Set(dataList.map((item: any) => item.region).filter(Boolean));
    regionList.value = Array.from(regions).sort();
  } catch (error) {
    console.error('获取地域列表失败:', error);
    regionList.value = [];
  } finally {
    regionLoading.value = false;
  }
};

/** 获取档位列表 */
const getGradeList = async () => {
  gradeLoading.value = true;
  try {
    const res = await listTable(queryParams.value);
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      dataList = res.rows;
    }
    
    if (queryParams.value.region) {
      dataList = dataList.filter((item: any) => item.region === queryParams.value.region);
    }
    if (queryParams.value.brand) {
      dataList = dataList.filter((item: any) => item.brand === queryParams.value.brand);
    }
    if (queryParams.value.category) {
      dataList = dataList.filter((item: any) => item.product_type === queryParams.value.category);
    }
    
    const grades = new Set(dataList.map((item: any) => item.grade).filter(Boolean));
    const gradeArray = Array.from(grades);
    
    const gradeOrder = ['一档', '二档', '三档', '四档', '五档', '六档', '七档', '八档', '九档', '十档'];
    gradeList.value = gradeArray.sort((a, b) => {
      const indexA = gradeOrder.indexOf(a);
      const indexB = gradeOrder.indexOf(b);
      
      if (indexA !== -1 && indexB !== -1) {
        return indexA - indexB;
      }
      if (indexA !== -1) return -1;
      if (indexB !== -1) return 1;
      return a.localeCompare(b, 'zh-CN');
    });
  } catch (error) {
    console.error('获取档位列表失败:', error);
    gradeList.value = [];
  } finally {
    gradeLoading.value = false;
  }
};

/** 获取品牌列表 */
const getBrandList = async () => {
  brandLoading.value = true;
  try {
    const res = await listTable(queryParams.value);
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      dataList = res.rows;
    }
    
    if (queryParams.value.region) {
      dataList = dataList.filter((item: any) => item.region === queryParams.value.region);
    }
    if (queryParams.value.grade) {
      dataList = dataList.filter((item: any) => item.grade === queryParams.value.grade);
    }
    if (queryParams.value.category) {
      dataList = dataList.filter((item: any) => item.product_type === queryParams.value.category);
    }
    
    const brands = new Set(dataList.map((item: any) => item.brand).filter(Boolean));
    brandList.value = Array.from(brands).sort();
  } catch (error) {
    console.error('获取品牌列表失败:', error);
    brandList.value = [];
  } finally {
    brandLoading.value = false;
  }
};

/** 获取种类列表 */
const getCategoryList = async () => {
  categoryLoading.value = true;
  try {
    const res = await listTable(queryParams.value);
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      dataList = res.rows;
    }
    
    if (queryParams.value.region) {
      dataList = dataList.filter((item: any) => item.region === queryParams.value.region);
    }
    if (queryParams.value.grade) {
      dataList = dataList.filter((item: any) => item.grade === queryParams.value.grade);
    }
    if (queryParams.value.brand) {
      dataList = dataList.filter((item: any) => item.brand === queryParams.value.brand);
    }
    
    const categories = new Set(dataList.map((item: any) => item.product_type).filter(Boolean));
    categoryList.value = Array.from(categories).sort();
  } catch (error) {
    console.error('获取种类列表失败:', error);
    categoryList.value = [];
  } finally {
    categoryLoading.value = false;
  }
};

/** 获取商品列表 */
const getProductList = async () => {
  productLoading.value = true;
  try {
    const res = await listTable(queryParams.value);
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      dataList = res.rows;
    }
    
    if (queryParams.value.region) {
      dataList = dataList.filter((item: any) => item.region === queryParams.value.region);
    }
    if (queryParams.value.grade) {
      dataList = dataList.filter((item: any) => item.grade === queryParams.value.grade);
    }
    if (queryParams.value.brand) {
      dataList = dataList.filter((item: any) => item.brand === queryParams.value.brand);
    }
    if (queryParams.value.category) {
      dataList = dataList.filter((item: any) => item.product_type === queryParams.value.category);
    }
    
    const products = dataList
      .map((item: any) => item.product_name)
      .filter((name: string) => name);
    
    productList.value = Array.from(new Set(products));
  } catch (error) {
    console.error('获取商品列表失败:', error);
    productList.value = [];
  } finally {
    productLoading.value = false;
  }
};

/** 商品搜索 */
const handleProductSearch = async (searchValue: string) => {
  if (!searchValue) {
    await getProductList();
    return;
  }
  
  productLoading.value = true;
  try {
    const res = await listTable(queryParams.value);
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      dataList = res.rows;
    }
    
    if (queryParams.value.region) {
      dataList = dataList.filter((item: any) => item.region === queryParams.value.region);
    }
    if (queryParams.value.grade) {
      dataList = dataList.filter((item: any) => item.grade === queryParams.value.grade);
    }
    if (queryParams.value.brand) {
      dataList = dataList.filter((item: any) => item.brand === queryParams.value.brand);
    }
    if (queryParams.value.category) {
      dataList = dataList.filter((item: any) => item.product_type === queryParams.value.category);
    }
    
    const products = dataList
      .map((item: any) => item.product_name)
      .filter((name: string) => name && name.includes(searchValue));
    
    productList.value = Array.from(new Set(products));
  } catch (error) {
    console.error('搜索商品失败:', error);
    productList.value = [];
  } finally {
    productLoading.value = false;
  }
};

onMounted(() => {
  getList();
  getRegionList();
  getGradeList();
  getBrandList();
  getCategoryList();
  getProductList();
});
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
